"""
convert `physics.xlsx` to `physics.md`
"""
import openpyxl as excel
from bs4 import BeautifulSoup


def read_xls(filename):
    laureates = {}
    wb = excel.load_workbook(filename)
    ws = wb.active
    for row in ws.iter_rows(min_row=2):
        laureate = {}
        laureate["name"] = row[1].value
        laureate["link"] = row[1].hyperlink.target
        laureate["birth"] = row[2].value
        laureate["birth_country"] = row[3].value
        laureate["status"] = row[4].value
        laureate["affiliation"] = row[5].value
        laureate["affiliation_country"] = row[6].value
        laureate["motivation"] = row[7].value
        laureate["work"] = row[8].value
        year = row[0].value
        if laureates.get(year) is None:
            laureates[year] = [laureate]
        else:
            laureates[year].append(laureate)
    return laureates


def html_to_markdown(html):
    soup = BeautifulSoup(html, 'html.parser')
    markdown = ''
    for p in soup.find_all('p'):
        markdown += '\t' + p.get_text() + '\n\n'
    return markdown


if __name__ == "__main__":
    laureates = read_xls("physics.xlsx")
    with open('physics.md', 'w') as file:
        for year in laureates:
            file.write('## **' + year + '**\n')
            laureates_of_year = laureates.get(year)
            for laureate in laureates_of_year:
                file.write('### [' + laureate.get('name') + '](' + laureate.get('link') + ') ')
                if laureate.get('status') == 'Deceased':
                    file.write(" <span style='color:grey;font-weight:lighter'>(" + laureate.get('status') + ')</font>')
                file.write('\n')
                file.write('  * **Born**: ' + laureate.get('birth') + ', ' + laureate.get('birth_country') + '\n')
                file.write('  * **Affiliation**: ' + laureate.get('affiliation') + ', ' + laureate.get(
                    'affiliation_country') + '\n')
                file.write('  * **Motivation**  \n\t' + laureate.get('motivation') + '\n')
                file.write('  * **Work**  \n' + html_to_markdown(laureate.get('work')))
